<?php

/*
 * Copyright 2018 zhuo bing.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

namespace backend\module\content\controllers;
use Yii;
use backend\module\content\models\Page;
use backend\module\content\models\ContentCategory;
use backend\module\content\controllers\ContentBaseController;
use backend\models\BackendUser;
/**
 * Description of PageController
 *
 * @author zhuo bing
 */
class PageController extends ContentBaseController{
    public function actionIndex($catid){
        $request = Yii::$app->request;
        $model =$this->findModel($catid);
        if(empty($model)){
            $model = new Page();
            $model->catid = $catid;
            $model->userid =    BackendUser::getParentUserId();
        }
        if($request->isPost && $model->load($request->post()) && $model->save()){
            return $this->redirect();
        }
        
        $data = ContentCategory::getAllData(BackendUser::getParentUserId());
        $ztreeNode = json_encode(ContentCategory::getZtreeNode($data, $catid));
        $model->created = $model->created?date('Y-m-d H:i:s',$model->created):null;
        return $this->render('create',[
            'ztreeNode' => $ztreeNode,
           'model'=>$model, 
        ]);
    }

    /**
     * Finds the Article model based on its primary key value.
     * If the model is not found, a 404 HTTP exception will be thrown.
     * @param integer $id
     * @return Article the loaded model
     * @throws NotFoundHttpException if the model cannot be found
     */
    protected function findModel($id) {
        $userid = BackendUser::getParentUserId();
        if (($model = Page::findOne(['catid' => $id, 'userid' => $userid])) !== null) {
            return $model;
        } 
        return false;
    }    
}
